require("../common/common.scss");
require("./index.scss")
var PaginationX = require("COMMON/modules/pagination-x/v1.0");
var loading = require('COMMON/js/util.loading.pc.js');
var ParseTemplate = ZFT.Util.ParseTemplate;
var Select = require("COMMON/modules/select/index.1.0");
var Toast = require('COMMON/modules/Toast');
var BankList = require("../common/zft.bank.data");
var cData = require("COMMON/js/config.province.city.data");
var toast = new Toast;
var STip = ZFT.Util.STip;
var Ajax = ZFT.Util.Ajax;
var Template = {
    tr: ParseTemplate(require("./tpl/tr.xtpl")),
    billDetail: ParseTemplate(require("./tpl/detail.xtpl")),
    additem: ParseTemplate(require("./tpl/detail_add_item.xtpl")),
    gather: ParseTemplate(require("./tpl/gathering.xtpl")),
    urge: ParseTemplate(require("./tpl/urge.xtpl")),
    freetr: ParseTemplate(require("./tpl/freemoneytr.xtpl")),
    buildingSelet: ParseTemplate(require("./tpl/allbuildings.xtpl"))
};

var Main = ZFT.Util.Class({
    PAGE_SIZE: 15,

    selectedContract: [],

    FEE_TYPE: [
        '房租',
        '物业',
        '水',
        '电',
        '公摊水',
        '公摊电',
        '税费',
        '其他费用'
    ],

    dom: {
        filter: '#filter',
        beginDate: '#beginDate',
        endDate: '#endDate',
        state: '#state',
        btnQuery: '#btnQuery',
        checkAll: '#checkAll',
        tbBill: '#tbBill',
        btnPay: '#btnPay',
        pagination: $(".paginationWrap"),
        billDetail: '#billDetail',
    },

    xhrGetBillList: null,

    init: function () {
        var _this = this;

        var dom = _this.dom;
        this.params = {
            begin_month: '',
            end_month: '',
            status: '0',
            page: 1,
            page_size: this.PAGE_SIZE,
            building_id: $("#buildingSelect").val(),
            room: $("#room").val()
        };

        this.ajaxGetBillList(this.params);
        _this.loadAllBuildings();
        $('#beginDate').datepicker({
            format: "yyyymm",
            startView: 1,
            minViewMode: 1,
            maxViewMode: 2,
            language: "zh-CN",
            autoclose: true
        });

        $('#endDate').datepicker({
            format: "yyyymm",
            startView: 1,
            minViewMode: 1,
            maxViewMode: 2,
            language: "zh-CN",
            autoclose: true
        });

        // $( this.dom.checkAll ).on('click', function(){

        //     if( $(this).prop('checked') ) {
        //         _this.selectContract();
        //     } else {
        //         _this.unSelectContract();
        //     }

        // });

        $(this.dom.tbBill).on('click', '.btn-getdetail', function (e) {

            var id = $(e.target).attr('data-id'),
                status = $(e.target).attr('data-status'),
                begin_cycle = $(e.target).attr('data-bcycle'),
                end_cycle = $(e.target).attr('data-ecycle');
            $('#feeDetail,#addFeeTbody tr').hide();
            _this.ajaxGetBillDetail(id, status, begin_cycle, end_cycle);


        });
        // .on('click', 'tbody :checkbox', function(){

        //     if( $(this).prop('checked') ) {
        //         _this.selectContract( $(this).attr('data-id') );
        //     } else {
        //         _this.unSelectContract( $(this).attr('data-id') );
        //     }

        // });

        $(this.dom.btnQuery).on('click', function () {
            var beginDate = $.trim($(_this.dom.beginDate).val()),
                endDate = $.trim($(_this.dom.endDate).val());
            var page_size = $(".paginationWrap").attr("data-size");
            if (beginDate > endDate) {
                STip('fail', '起始时间不能大于结束时间');
                return false;
            }

            if ($(_this.dom.state).val() == 1) {
                $(_this.dom.btnPay).hide();
            } else {
                $(_this.dom.btnPay).show();
            }

            _this.params = {
                begin_month: beginDate,
                end_month: endDate,
                status: $(_this.dom.state).val(),
                page: 1,
                page_size: page_size ? page_size : _this.PAGE_SIZE,
                building_id: $("#buildingSelect").val(),
                room: $("#room").val()
            };

            // console.log(_this.params)
            // _this.selectedContract = [];
            _this.ajaxGetBillList(_this.params);
        });

        // $( this.dom.btnPay ).on('click', function(){
        //     if( _this.selectedContract.length ) {
        //         location.href = 'pay?ids=' + _this.selectedContract.join()
        //     } else {
        //         STip('fail','至少选择一个账单');
        //     }
        // });

        $(this.dom.billDetail).on("click", ".close,.cancel", function (e) {
            var tarBtn = $(e.currentTarget);
            tarBtn.parents(".m-modal_bg").fadeOut(200);
        })
    },

    ajaxGetBillList: function (params) {
        var _this = this;

        this.xhrGetBillList = this.ajaxRenderData({
            container: this.dom.tbBill + ' tbody',
            url: '/r/BillManager_leaseBill',
            params: params,
            loading: {
                id: 'billLoading',
                text: '正在努力加载您的账单...',
                className: 'tb-loading',
                colspan: 8,
                tag: 'td',
                hidePage: function () {
                    $(".paginationWrap").hide();
                }
            },
            success: function (res) {
                _this.renderBillList(res.data.list);


                if (_this.pagination) {

                    _this.pagination.render({ current: res.data.current_page, total: res.data.total });

                } else {

                    _this.pagination = new PaginationX({
                        container: $(".paginationWrap"),
                        count: 7,
                        showTotal: true,
                        jump: true,
                        filter: true
                    });

                    _this.pagination.on("page.switch", function (toPage, current, total) {
                        var page_size = $(".paginationWrap").attr("data-size");
                        $(_this.dom.checkAll).prop('checked', false);

                        _this.params.page = toPage;
                        _this.params.page_size = page_size ? page_size : 15;
                        _this.ajaxGetBillList(_this.params);

                    });

                    _this.pagination.render({ current: res.data.current_page, total: res.data.total });

                }
            },
            error: function (res) {
                $(_this.dom.tbBill + ' tbody').html('<tr><td colspan="8" align="center" class="tb-nodata">' + res.msg + '</td></tr>');
            }
        })
    },
    ajaxRenderData: function (opts) {
        return Ajax(opts.url, {
            type: 'POST',
            params: opts.params,
            loading: function () {
                var loadingOpts = {};

                loadingOpts.id = opts.loading.id;
                loadingOpts.text = opts.loading.text || '';
                loadingOpts.className = opts.loading.className;
                loadingOpts.tag = opts.loading.tag || '';
                if (opts.loading.tag == 'td') {
                    loadingOpts.colspan = opts.loading.colspan ? opts.loading.colspan : '';
                }

                var html = loading(opts.loading.text, loadingOpts);
                $(opts.container).html(html);
                if (opts.loading.hidePage) opts.loading.hidePage()
            },
            success: function (res) {
                $('#' + opts.loading.id).remove();


                if (res.code == 200 || res.code == 'success') {
                    opts.success && opts.success(res);
                } else {

                    opts.error && opts.error(res);
                }
            },
            serverError: function (xhr, txt) {

            }
        })
    },

    renderBillList: function (data) {
        var html,
            _this = this,
            pers = ZFT.Util.getPermission(),
            btnPer;
        btnPer = ($.inArray("28", pers) !== -1) ? 1 : 0
        data["perBtn"] = btnPer;
        html = Template.tr({ data: data });
        $(_this.dom.tbBill + ' tbody').html(html);
        _this.sendUrgeMessage();
        _this.gatherByGuy();

    },

    ajaxGetBillDetail: function (id, status, begin_cycle, end_cycle) {
        var _this = this;

        this.xhrGetBillDetail = this.ajaxRenderData({
            container: this.billDetail,
            url: '/r/BillManager_leaseBillDetail',
            params: {
                id: id,
                status: status,
                begin_cycle: begin_cycle,
                end_cycle: end_cycle

            },
            loading: {
                id: 'billDetailLoading',
                text: '正在努力加载您的账单明细...',
                className: 'tb-loading',
                colspan: 2,
                tag: 'td'
            },
            success: function (res) {
                _this.renderBillDetail(res.data, id, status);
            },
            error: function (res) {
                $(_this.dom.tbBillDetail + ' tbody').html('<tr><td colspan="10" align="center" class="tb-nodata">' + res.msg + '</td></tr>');
            }
        })
    },
    renderBillDetail: function (data, id, status) {
        var _this = this;
        var list = data.list;
        for (var i = 0, dataLen = list.length; i < dataLen; i++) {
            list[i].type = _this.FEE_TYPE[list[i].type_money - 1]
        }
        var begin_cycle = list[0].begin_cycle,
            end_cycle = list[0].end_cycle;
        var dtype = ZFT.Util.getDtype();
        var html;
        var billItem = Template.additem({ data: _this.FEE_TYPE });
        var saveMoneyData = {
            begin_cycle: begin_cycle,
            end_cycle: end_cycle,
            id: id,
            status: status
        }
        var pers = ZFT.Util.getPermission();
        data["freePer"] = ($.inArray("46", pers) !== -1) ? 1 : 0;
        data["newBillPer"] = ($.inArray("47", pers) !== -1) ? 1 : 0;
        html = Template.billDetail({ data: data, begin_cycle: begin_cycle, end_cycle: end_cycle, dtype: dtype, status: status })
        $(_this.dom.billDetail).html(html);
        _this.saveFreeMoney(saveMoneyData);
        //添加费用项目
        $("#addFeeBtn").on("click", function () {
            var controlBox = $("#controlBox");
            var tbody = $("#tbody");
            if (!controlBox.is(":visible")) {
                controlBox.css("display", "inline-block");
            }
            tbody.append(billItem);
            $(".u-dtl-item").on("change", function (e) {
                var tarSelect = $(e.currentTarget);
                var tarVal = tarSelect.val();
                var parents = tarSelect.parents(".item-tr");
                if (tarVal != -1) {
                    parents.find(".i-inp").removeAttr("readonly").attr("placeholder", "").val("");
                    parents.find(".inp-name").val(_this.FEE_TYPE[tarVal - 1]);

                } else {
                    parents.find(".i-inp").attr({ "readonly": "readonly", "placeholder": "请先选择费用类型" }).val("");
                }
            })
            $(".btn-del").on("click", function (e) {
                var tarBtn = $(e.currentTarget);
                tarBtn.parents(".item-tr").fadeOut(150, function () {
                    this.remove();
                })

            });
            $("#saveBtn").off("click");
            $("#saveBtn").on("click", function (e) {
                var arr = [];
                var tarBtn = $(e.currentTarget);
                var $itemTr = $(".item-tr");
                var comment = $("#comment").val();
                var param;
                var params = {
                    begin_month: '',
                    end_month: '',
                    status: '',
                    page: 1,
                    page_size: _this.PAGE_SIZE
                }
                var regFee = /^(\d*\.)?\d+$/;;
                for (var i = 0, len = $itemTr.length; i < len; i++) {
                    var type = $itemTr.eq(i).find(".u-dtl-item").val();
                    var billname = $itemTr.eq(i).find(".inp-name").val();
                    var value = $itemTr.eq(i).find(".inp-fee").val();
                    if (type != -1) {
                        if (!billname) return STip("fail", "请输入费用项目名称！");
                        if (!regFee.test(value)) return STip("fail", "请输入正确的费用金额！");
                        arr.push({ "type": type, "value": value, "bill_name": billname });
                    }
                };
                if (arr.length <= 0) return STip("fail", "请输入费用信息！");
                param = {
                    id: id,
                    begin_cycle: begin_cycle,
                    end_cycle: end_cycle,
                    array: JSON.stringify(arr)
                }
                if (comment) param["comment"] = comment;
                Ajax("/r/BillManager_addPayBill", {
                    type: "POST",
                    dataType: "json",
                    params: param,
                    loading: function () {
                        tarBtn.attr("disabled", "disabled").removeClass("m-btn_primary");
                    },
                    success: function (res) {
                        if (res.code == 200) {
                            STip("success", res.msg);
                            $(_this.dom.billDetail).html("");
                            _this.ajaxGetBillList(params);
                        } else {
                            STip("fail", res.msg);
                            tarBtn.removeAttr("disabled").addClass("m-btn_primary");
                        }
                    }
                })
            })
        });
    },
    //保存优惠金额
    saveFreeMoney: function (data) {
        //新增优惠金额
        var _this = this;
        $("#detailTbody .btn-save").on("click", function (e) {
            var tarbtn = $(e.currentTarget),
                iid = tarbtn.attr("data-id"),
                free_money = tarbtn.siblings(".u-inp_free_money").val(),
                regFee = /^(\d*\.)?\d+$/;
            if (!regFee.test(free_money)) return STip("fail", "优惠金额格式错误！");
            Ajax("/r/BillManager_addDiscount", {
                type: "POST",
                dataType: "json",
                params: {
                    id: iid,
                    free_money: free_money
                },
                loading: function () {
                    tarbtn.attr("disabled", "disabled");
                },
                complete: function () {
                    tarbtn.removeAttr("disabled");
                },
                success: function (res) {
                    if (res.code == 200) {
                        STip("success", res.msg);
                        _this.refeshFreeMoney(data);
                    } else {
                        STip("fail", res.msg);
                    }
                }
            })
        })
    },

    //刷新详情table
    refeshFreeMoney: function (param) {
        var _this = this,
            tbody = $("#detailTbody")
        Ajax("/r/BillManager_leaseBillDetail", {
            type: "POST",
            dataType: "json",
            params: param,
            loading: function () {
                var loading = '<tr><td colspan="6">加载中，请稍候...</td></tr>';
                tbody.html(loading);
            },
            success: function (res) {
                if (res.code == 200) {
                    var data = res.data;
                    var list = data.list;
                    for (var i = 0, dataLen = list.length; i < dataLen; i++) {
                        list[i].type = _this.FEE_TYPE[list[i].type_money - 1]
                    }
                    var html = Template.freetr({ data: data });
                    tbody.html(html);
                    _this.saveFreeMoney(param);
                } else {
                    var error = '<tr><td colspan="6">' + res.msg + '</td></tr>';
                    tbody.html(error);
                }
            }
        })
    },
    loadAllBuildings: function () {
        ZFT.Util.Ajax("/r/Building_getOwnerBuilding", {
            type: "POST",
            dataType: "json",
            success: function (res) {
                if (res.code == 200) {
                    var html = Template.buildingSelet({ data: res.data });
                    $("#buildingSelect").html(html);
                }
            }
        })
    },
    selectContract: function (id) {
        var allCheckbox = $(this.dom.tbBill + ' tbody').find(':checkbox');

        if (id === undefined) {
            allCheckbox.prop('checked', true);

            var checkedArr = allCheckbox.map(function () {
                return $(this).attr('data-id');
            });

            this.selectedContract = this.concatArr(this.selectedContract, checkedArr);
        } else {
            if (this.selectedContract.indexOf(id) == -1) {
                this.selectedContract.push(id);

                if (allCheckbox.filter(':checked').length == allCheckbox.length) {
                    $(this.dom.checkAll).prop('checked', true);
                }
            }
        }
    },
    unSelectContract: function (id) {
        var _this = this;

        if (id === undefined) {

            var allCheckbox = $(this.dom.tbBill + ' tbody').find(':checkbox');

            allCheckbox.prop('checked', false);

            allCheckbox.each(function (i) {
                if (_this.selectedContract.indexOf($(this).attr('data-id')) != -1) {
                    _this.selectedContract.splice(_this.selectedContract.indexOf($(this).attr('data-id')), 1);
                }
            });

        } else {

            if (this.selectedContract.indexOf(id) != -1) {
                this.selectedContract.splice(this.selectedContract.indexOf(id), 1);
            }

            $(_this.dom.checkAll).prop('checked', false);
        }
    },
    concatArr: function (arr1, arr2) {
        arr1.push.apply(arr1, arr2);

        var n = {}, r = []; //n为hash表，r为临时数组
        for (var i = 0; i < arr1.length; i++) //遍历当前数组
        {
            if (!n[arr1[i]]) //如果hash表中没有当前项
            {
                n[arr1[i]] = true; //存入hash表
                r.push(arr1[i]); //把当前数组的当前项push到临时数组里面
            }
        }

        return r;
    },
    //点击添加费用明细时筛选添加权限
    /* checkFee: function (arr) {
         var saveBtn = $("#saveBtn");
         if (arr.length === 0) {
             saveBtn.hide();
             return false;
         }
         saveBtn.show();
         for (var i in arr) {
             $("#addFeeTbody tr[data-id=" + arr[i] + "]").show();
         }
 
     },
     //添加费用明细
     addFeeDetail: function (id, add_type, status) {
         var _this = this;
         var saveBtn = $("#saveBtn");
         // saveBtn.off("click");
         saveBtn.on("click", function () {
             var arr = [];
             var brr = {};
             var feeVal = '';
             for (var i = 0, len = add_type.length; i < len; i++) {
                 feeVal = $("#addFeeTbody input[data-id=" + add_type[i] + "]").val();
                 // console.log(feeVal);
                 if ($.trim(feeVal) == "") {
                     STip("fail", "请将信息填写完整!", 1000);
                     break;
                 }
                 brr = { 'type': add_type[i], 'value': feeVal }
                 arr.push(brr)
             }
             if (i != len) return false;
             var array = JSON.stringify(arr);
             _this.saveFee(id, array);
         });
     },*/
    //保存公摊水电
    saveFee: function (id, array) {
        var _this = this;
        Ajax(
            '/r/BillManager_addPayBill',
            {
                type: "POST",
                dataType: "json",
                params: {
                    id: id,
                    array: array
                },
                success: function (res) {
                    if (res.code == 200) {
                        $("#feeDetail").hide();
                        $("#addFeeTbody input").val('');
                        _this.ajaxGetBillDetail(id, status);
                        STip("success", res.msg, 3000);
                    } else if (res.code == 102) {
                        return STip("fail", "未登录,请重新登录", 4000, function () {
                            window.location.href = "/index/index/login";
                        });
                    } else {
                        return STip("fail", res.msg, 3000);
                    }
                }
            })
    },
    //人工确认收款
    gatherByGuy: function () {
        var _this = this;
        var billDetail = $(_this.dom.billDetail);
        $(".btn-conf").on("click", function (e) {
            var confBtn = $(e.currentTarget);
            var begin_cycle = confBtn.attr("data-b");
            var ordernum = confBtn.attr("data-id");
            var end_cycle = confBtn.attr("data-e");
            var param = {
                ordernum: ordernum,
                begin_cycle: begin_cycle,
                end_cycle: end_cycle
            }
            Ajax("/r/BillManager_getManualCollection", {
                type: "POST",
                dataType: "json",
                params: param,
                success: function (res) {
                    var data = res.data;
                    if (res.code == 200) {
                        var locationName = _this.getLocationName(data.province, data.city);
                        var modal;
                        data["locationName"] = locationName;
                        data["begin_cycle"] = begin_cycle;
                        data["end_cycle"] = end_cycle;
                        modal = Template.gather({ data: data });
                        billDetail.html(modal);
                        _this.initBank()
                        $("#payment").on("change", function (e) {
                            var tar = $(e.currentTarget);
                            var tarVal = tar.val();
                            $("#payDate,#serialNumInp").val("");
                            $("#bankBox").css("display", (tarVal == 3) ? "inline-block" : "none");
                        });
                        $("#payDate").datepicker({
                            format: "yyyymmdd",
                            maxViewMode: 2,
                            language: "zh-CN",
                            autoclose: true
                        });
                        $("#saveBtn").on("click", function (e) {
                            var pay_type = $("#payment").val();
                            var serial_number = $("#serialNumInp").val();
                            var pay_time = $("#payDate").val();
                            var regTime = /^\d{8}$/;
                            var param;
                            if (pay_type != 0 && !serial_number) return STip("fail", "请输入支付流水号");
                            if (!regTime.test(pay_time)) return STip("fail", "请选择实际支付日期！");
                            if (pay_type != 3 && $("#bankInp").is(":visible")) {
                                return STip("Oops!你做了错误的操作！");
                            }
                            param = {
                                ordernum: ordernum,
                                begin_cycle: begin_cycle,
                                end_cycle: end_cycle,
                                order_id: JSON.stringify(data.order_id),
                                pay_type: pay_type,
                                serial_number: serial_number,
                                pay_time: pay_time
                            }
                            if (pay_type == 3) {
                                param["pay_type"] = $("#bankInp").val();
                            }
                            Ajax("/r/BillManager_setManualCollection", {
                                type: "POST",
                                dataType: "json",
                                params: param,
                                success: function (res) {
                                    if (res.code == 200) {
                                        STip("success", "确认收款成功！");
                                        billDetail.html("");
                                        _this.ajaxGetBillList(_this.params);
                                    } else {
                                        return STip("fail", res.msg);
                                    }

                                }
                            })
                        })

                    } else {
                        return STip("fail", res.msg);
                    }
                }
            })
        })
    },
    //催缴短信
    sendUrgeMessage: function () {
        var _this = this;
        $(".btn-urge").on("click", function (e) {
            var tarBtn = $(e.currentTarget);
            var html;
            var begin_cycle = tarBtn.attr("data-b");
            var end_cycle = tarBtn.attr("data-e");
            var order_id = JSON.stringify(tarBtn.attr("data-oid").split(","));
            var ordernum = tarBtn.attr("data-id");
            var param = {
                order_id: order_id,
                ordernum: ordernum,
                begin_cycle: begin_cycle,
                end_cycle: end_cycle,
                send_status: 0
            }
            Ajax("/r/PayNoticeList_manualSend", {
                type: "POST",
                dataType: "json",
                params: param,
                success: function (res) {
                    if (res.code == 200) {
                        html = Template.urge({ data: res.data });
                        $(_this.dom.billDetail).html(html);
                        $("#sendBill").on("click", function (e) {
                            var tarBtn = $(e.currentTarget);
                            param["send_status"] = 1;
                            _this.confSendSMS(param);
                            tarBtn.off("click");
                        });
                    } else {
                        return STip("fail", res.msg);
                    }
                }
            })

        })
    },
    confSendSMS: function (param) {
        var _this = this;
        Ajax("/r/PayNoticeList_manualSend", {
            type: "POST",
            dataType: "json",
            params: param,
            success: function (res) {
                if (res.code == 200) {
                    STip("success", "发送成功！");
                    $(_this.dom.billDetail).html("");
                } else {
                    return STip("fail", res.msg);
                }
            }
        })
    },
    //通过区域码获取对应名称
    getLocationName: function (prov, cityId) {
        var province = cData[prov];
        var prov_name = province.name;
        var citys = province.city;
        var city_name = "";
        for (var i = 0; i < citys.length; i++) {
            var city = citys[i];
            var city_id = city.id;
            if (city_id == cityId) {
                city_name = city.name;
                break;
            }
        }
        return prov_name + city_name;
    },
    //初始化银行
    initBank: function () {
        var _this = this;
        var html;
        for (var i in BankList) {
            html += "<option value=" + BankList[i].id + ">" + BankList[i].name + "</option>";
        }
        $("#bankInp").html(html);
    },

});
$(function () {
    new Main();
})